<template>
  <div class="filter">
    <!-- <el-row class="header">
      <el-col
        style="margin-top: 20px; margin-right: 20px; height: 302px; width: 361px;"
        scoped
        v-for="(file, index) in biopsyList"
        :key="index"
      >
        <el-card :body-style="{ padding: '20px' }">
          <el-row>
            <div @click="exclude(file)">
              <img :src="PathologyFilesServer + file.labelUrl" class="image" />
              <img
                :src="PathologyFilesServer + file.previewUrl"
                class="image"
              />
            </div>
          </el-row>
          <el-row class="item">
            <span>上传者：</span>
            <span>{{ file.createUser }}</span>
          </el-row>
          <el-row class="item">
            <span>切片描述：</span>
            <span v-if="!file.description">暂无</span>
            <span v-else>{{ file.description }}</span>
          </el-row>
          <el-row class="item">
            <span>上传时间：</span>
            <span>{{ file.createTime }}</span>
          </el-row>
        </el-card>
      </el-col>
    </el-row> -->
    <el-form :model="tempPathologyFiles">
      <el-form-item
        label=""
        prop="Files"
        :rules="[{ required: true, message: ' ', trigger: 'blur' }]"
      >
        <!-- <el-button
                    @click="uploadPathology"
                    size="small"
                    type="primary"
                >点击上传</el-button> -->

        <el-row
          v-for="(file, index) in tempPathologyFiles.Files"
          :key="index"
          class="pathology-preview"
        >
          <div @click="exclude(file)">
            <img :src="PathologyFilesServer + file.labelUrl" class="image" />
            <img :src="PathologyFilesServer + file.previewUrl" class="image" />
          </div>
          <!-- <div class="pathology-info">
                            <el-input
                                type="textarea"
                                :rows="4"
                                placeholder="请输入描述"
                                v-model="file.description"
                            ></el-input>
                        </div> -->
          <!-- <el-button
                            type="primary"
                            size="mini"
                            @click="downloadPathology(file)"
                            style="margin: 0 auto 0 20px"
                        >下载切片</el-button> -->
        </el-row>
      </el-form-item>
      <!-- <div style="margin-top: 6px; text-align: center">
                <el-button
                    type="primary"
                    size="mini"
                    @click="onPathologyDataClick"
                >提交</el-button>
            </div> -->
    </el-form>
  </div>
</template>

<script>
import VueDraggable from 'vuedraggable'
import * as Uppy from 'uppy'
import 'uppy/dist/uppy.min.css'
const Chinese = require('@uppy/locales/lib/zh_CN')
export default {
  name: 'ConsultationPathology',
  props: ['orders'],
  components: {
    VueDraggable
  },
  data() {
    return {
      // 切片服务地址
      PathologyFilesServer: process.env.VUE_APP_pathologyServiceURL,
      tempPathologyFiles: { Files: [] }
    }
  },
  mounted() {
    this.__initUppy()
    let fileList = []
    if (
      this.orders.patients[0].diagnosisHistory.length > 0 &&
      this.orders.patients[0].diagnosisHistory[0].diagnosisDataInfos
    ) {
      this.orders.patients[0].diagnosisHistory[0].diagnosisDataInfos.forEach(item => {
        if (item.fileType == 3) {
          fileList.push({
            labelUrl: item.labelAddress,
            previewUrl: item.preFileAddress,
            newFilename: item.dziAddress,
            originFilename: item.fileAddress,
            createTime: item.createTime,
            createUser: item.createUser,
            fileType: 3,
            description: item.description
          })
        }
      })
    }

    this.tempPathologyFiles.Files = fileList
  },

  methods: {
    downloadPathology(file) {
      let _this = this
      const loading = _this.$loading({
        lock: true,
        text: '下载中......',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let url = `${_this.PathologyFilesServer}/download/${file.originFilename}`
      // let first = url.lastIndexOf('.') //取到文件名开始到最后一个点的长度
      // let nameLength = url.length //取到文件名长度
      // let fileSuffix = url.substring(first + 1, nameLength) //截取获得后缀名
      const x = new XMLHttpRequest()
      x.open('GET', url, true)
      x.responseType = 'blob'
      x.onload = function(e) {
        // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
        const mUrl = window.URL.createObjectURL(x.response)
        const a = document.createElement('a')
        a.href = mUrl
        a.download = file.originFilename
        a.click()
        loading.close()
      }
      x.send()
    },
    onPathologyDataClick() {
      let Data = {
        patientId: this.orders.patients[0].id,
        id: this.orders.patients[0].diagnosisHistory[0].id, //病人诊断历史ID
        deleteFileType: 3,
        createDiagnosisDataParameters: this.tempPathologyFiles.Files.map(item => {
          return {
            diagnosisHistoryId: null,
            fileAddress: item.originFilename,
            fileType: item.fileType,
            dziAddress: item.newFilename,
            labelAddress: item.labelUrl,
            preFileAddress: item.previewUrl,
            createTime: item.createTime,
            createUser: item.createUser,
            description: item.description
          }
        }) //病史资料图片
      }

      this.$axios({
        method: 'POST',
        url: `/diagnosis_history`,
        data: Data
      }).then(res => {
        if (res && res.data.code === 200) {
          this.$message.success('提交成功')
        }
      })
    },
    __initUppy() {
      let _this = this
      const mUppy = Uppy.Core({
        locale: Chinese,
        restrictions: {
          maxFileSize: null,
          maxNumberOfFiles: null,
          minNumberOfFiles: null,
          allowedFileTypes: ['.svs', '.mds', '.ndpi', '.sdpc', '.kfb']
        }
      })
      mUppy.use(Uppy.Dashboard, {
        proudlyDisplayPoweredByUppy: false,
        showProgressDetails: true,
        note: '仅支持 .svs/.mds/.ndpi/.sdpc /.kfb 格式文件'
      })
      mUppy.use(Uppy.XHRUpload, {
        timeout: 300 * 1000,
        endpoint: `${this.PathologyFilesServer}/upload`,
        fieldName: 'file',
        method: 'POST',
        formData: true,
        metaFields: ['biopsyHistoryId']
      })
      mUppy.on('file-added', file => {
        mUppy.setFileMeta(file.id, {
          biopsyHistoryId: this.resData.biopsyHistoryId
        })
      })
      mUppy.on('dashboard:modal-closed', () => {
        if (_this.tempPathologyFiles.Files.length == 0) {
          return false
        } else {
          _this.onPathologyDataClick()
        }
      })
      // 下载完成后预览图。标签预览图：labelUrl，图像预览图：previewUrl
      mUppy.on('upload-success', (file, response) => {
        this.tempPathologyFiles.Files.push({
          newFilename: response.body.dzi.replace('/data/waiting_folder', ''),
          labelUrl: response.body.info.replace('/data/waiting_folder', ''),
          previewUrl: response.body.preview.replace('/data/waiting_folder', ''),
          originFilename: response.body.file,
          fileType: 3,
          description: ''
        })
      })
      this.uppy = mUppy
    },
    uploadPathology() {
      this.uppy.reset()
      const dashboard = this.uppy.getPlugin('Dashboard')
      if (!dashboard.isModalOpen()) {
        dashboard.openModal()
      }
    },
    exclude(val) {
      const { href } = this.$router.resolve({
        name: 'shareViewer',
        path: '/shareViewer',
        query: {
          dzi: val.newFilename,
          originFilename: val.originFilename,
          authorization: this.$store.state.authorization,
          userId: this.$store.state.user.id,
          uuid: this.orders.uuid
        }
      })
      window.open(href, 'doctorWorkstation')
    }
  }
}
</script>

<style scoped>
.pathology-preview img {
  width: 146px;
  height: 146px;
}

.add-board {
  padding: 20px;
  background: #ffffff;
}

.pathology-preview a,
.pathology-preview div {
  float: left;
}

.pathology-preview div.pathology-info {
  margin-left: 10px;
}

.pathology-preview {
  padding: 5px;
  margin-top: 20px;
}

.filter {
  border-bottom: #f4f4f4 1px;

  padding: 10px 30px;

  background: #ffffff;
}

.image {
  height: 138px;

  width: 138px;

  margin-left: 15px;
}

.header {
  margin-top: 20px;

  font-size: 14px;
}

.item {
  margin-top: 10px;
  margin-left: 15px;

  align-items: center;
}
</style>
